#!/usr/bin/env python
#coding=utf-8
'''
Created on 2010-10-25

@author: Chine
'''
from django.contrib.syndication.views import Feed, add_domain
from django.contrib.sites.models import Site, RequestSite
from django.shortcuts import render_to_response, get_object_or_404
from django.utils.feedgenerator import rfc2822_date
from django.utils import tzinfo

from datetime import datetime, timedelta

from ChineKingBlog.blog.models import Article, Comment
from ChineKingBlog.blog.utils import get_article_abstract

add_cn_tzinfo = lambda dt: dt.replace(tzinfo=tzinfo.FixedOffset(timedelta(hours=8)))

class RSSFeed(Feed):    
    title = "chineking's blog"
    description = "Lost good things"
    link = "/"
    
    def items(self):
        return Article.objects.filter(status=2).order_by("-created")[:10]
    
    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.content
    
def feed(request):
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    
    items = Article.objects.filter(status=2).order_by("-created")[:10]
    link = add_domain(current_site.domain, '/')
    
    if(items.count() > 0):
        last_post_date = items[0].created;
    else:
        last_post_date = datetime.now()
    last_post_date = add_cn_tzinfo(last_post_date)       
    last_build_date = rfc2822_date(last_post_date)
    
    for item in items:
        item.link = add_domain(current_site.domain, item.get_absolute_url())
        item.pubdate = rfc2822_date(add_cn_tzinfo(item.created))
        item.description = get_article_abstract(item.content)
    
    return render_to_response('rss/rss.xml', locals())

def ArticleFeed(request, slug):
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    
    items = Comment.objects.filter(visible=True).order_by("-post_date")
    article = get_object_or_404(Article, slug=slug)
    link = add_domain(current_site.domain, article.get_absolute_url())
    title = article.title
    description = title
    
    if(items.count() > 0):
        last_post_date = items[0].post_date;
    else:
        last_post_date = datetime.now()
    last_post_date = add_cn_tzinfo(last_post_date)       
    last_build_date = rfc2822_date(last_post_date)
    
    for item in items:
        item.link = add_domain(current_site.domain, '/article/' + slug + '#comment-' + str(item.id))
        item.pubdate = rfc2822_date(add_cn_tzinfo(item.post_date))
        item.description = get_article_abstract(item.content)
        item.title = item.description
        item.author = item.username
    
    return render_to_response('rss/rss.xml', locals())